<template>
  <div class="my-learning-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <div class="navbar-left">
          <router-link to="/home" class="back-btn">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
            返回首页
          </router-link>
        </div>
        <div class="navbar-center">
          <h1>我的学习</h1>
        </div>
        <div class="navbar-right">
          <div class="user-info">
            <img 
              v-if="userInfo?.avatar" 
              :src="getAvatarUrl(userInfo.avatar)" 
              alt="头像" 
              class="user-avatar-small" 
              @click="handleAvatarClick"
              style="cursor: pointer;"
              title="点击更换头像"
            />
            <span 
              v-else 
              class="avatar-placeholder-small"
              @click="handleAvatarClick"
              style="cursor: pointer;"
              title="点击更换头像"
            >
              {{ userInfo?.nickname?.charAt(0) || '用' }}
            </span>
            <span class="user-name">{{ userInfo?.nickname || '未登录' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card">
        <div class="stat-icon">📝</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.totalProblems }}</div>
          <div class="stat-label">已做题目</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">✅</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.correctProblems }}</div>
          <div class="stat-label">正确题目</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">📊</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.accuracy }}%</div>
          <div class="stat-label">正确率</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">🔥</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.continuousDays }}</div>
          <div class="stat-label">连续学习</div>
        </div>
      </div>
    </div>

    <!-- 筛选标签 -->
    <div class="filter-container">
      <div class="filter-tabs">
        <button 
          :class="['filter-tab', { active: currentTab === 'all' }]"
          @click="changeTab('all')"
        >
          全部 ({{ localStats.total }})
        </button>
        <button 
          :class="['filter-tab', { active: currentTab === 'correct' }]"
          @click="changeTab('correct')"
        >
          已答对 ({{ localStats.correct }})
        </button>
        <button 
          :class="['filter-tab', { active: currentTab === 'wrong' }]"
          @click="changeTab('wrong')"
        >
          答错 ({{ localStats.wrong }})
        </button>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="content-container">
      <div v-if="loading" class="loading">
        <svg viewBox="0 0 24 24" width="40" height="40" fill="currentColor" class="spin">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-3.31 0-6 2.69-6 6h2c0-2.21 1.79-4 4-4V6z"/>
        </svg>
        <p>加载中...</p>
      </div>

      <div v-else-if="displayProblems.length === 0" class="empty">
        <svg viewBox="0 0 24 24" width="64" height="64" fill="currentColor" opacity="0.3">
          <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zM7 10h2v7H7zm4-3h2v10h-2zm4 6h2v4h-2z"/>
        </svg>
        <p>{{ currentTab === 'all' ? '暂无做题记录' : currentTab === 'correct' ? '暂无答对的题目' : '暂无答错的题目' }}</p>
      </div>

      <div v-else class="problems-list">
        <div 
          v-for="problem in displayProblems" 
          :key="problem.id"
          class="problem-item"
          @click="goToProblem(problem.problemId)"
        >
          <div class="problem-header">
            <div class="problem-id">题目 #{{ problem.problemId }}</div>
            <div :class="['problem-status', problem.isCorrect ? 'correct' : 'wrong']">
              {{ problem.isCorrect ? '✓ 答对' : '✗ 答错' }}
            </div>
          </div>
          <div class="problem-title">{{ problem.title }}</div>
          <div class="problem-meta">
            <span class="problem-difficulty" :class="problem.difficulty">
              {{ problem.difficulty === 'easy' ? '简单' : problem.difficulty === 'medium' ? '中等' : '困难' }}
            </span>
            <span class="problem-time">{{ formatTime(problem.submitTime) }}</span>
            <span v-if="problem.score" class="problem-score">得分: {{ problem.score }}</span>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="displayProblems.length > 0" class="pagination">
        <button 
          class="page-btn" 
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button 
          class="page-btn"
          :disabled="currentPage === totalPages"
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 隐藏的头像上传input -->
    <input 
      type="file" 
      ref="avatarInput" 
      accept="image/*" 
      style="display: none"
      @change="handleAvatarChange"
    />

    <!-- Toast提示 -->
    <Toast ref="toastRef" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getMyLearning, getLearningStats, uploadAvatar } from '../api/user'
import { getAvatarUrl } from '../utils/url'
import Toast from '../components/Toast.vue'

const router = useRouter()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const avatarInput = ref(null)
const toastRef = ref(null)
const loading = ref(false)
const currentTab = ref('all') // all, correct, wrong
const currentPage = ref(1)
const pageSize = 20

const problems = ref([])
const stats = ref({
  totalProblems: 0,
  correctProblems: 0,
  wrongProblems: 0,
  accuracy: 0,
  continuousDays: 0
})

// 去重：同一道题只保留最新的记录
const uniqueProblems = computed(() => {
  const problemMap = new Map()
  
  // 遍历所有记录，按题目ID去重，保留最新的
  problems.value.forEach(problem => {
    if (!problemMap.has(problem.problemId)) {
      problemMap.set(problem.problemId, problem)
    }
    // 如果已存在，比较时间，保留最新的
    else {
      const existing = problemMap.get(problem.problemId)
      if (new Date(problem.submitTime) > new Date(existing.submitTime)) {
        problemMap.set(problem.problemId, problem)
      }
    }
  })
  
  return Array.from(problemMap.values())
})

const displayProblems = computed(() => {
  let filtered = uniqueProblems.value
  
  if (currentTab.value === 'correct') {
    filtered = uniqueProblems.value.filter(p => p.isCorrect)
  } else if (currentTab.value === 'wrong') {
    filtered = uniqueProblems.value.filter(p => !p.isCorrect)
  }
  
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return filtered.slice(start, end)
})

const totalPages = computed(() => {
  let total = uniqueProblems.value.length
  
  if (currentTab.value === 'correct') {
    total = uniqueProblems.value.filter(p => p.isCorrect).length
  } else if (currentTab.value === 'wrong') {
    total = uniqueProblems.value.filter(p => !p.isCorrect).length
  }
  
  return Math.ceil(total / pageSize) || 1
})

onMounted(() => {
  loadLearningData()
})

async function loadLearningData() {
  loading.value = true
  try {
    // 加载统计数据
    const statsRes = await getLearningStats()
    console.log('📊 后端返回的统计数据:', statsRes)
    
    if (statsRes.code === 200) {
      console.log('✅ 统计数据详情:', statsRes.data)
      console.log('🔥 连续学习天数:', statsRes.data.continuousDays)
      stats.value = statsRes.data
    }
    
    // 加载题目列表
    const problemsRes = await getMyLearning()
    if (problemsRes.code === 200) {
      problems.value = problemsRes.data.list || []
      
      // 保存原始的连续学习天数
      const originalContinuousDays = stats.value.continuousDays
      
      // 使用本地计算的统计数据（去重后）
      stats.value = {
        ...stats.value,
        totalProblems: localStats.value.total,
        correctProblems: localStats.value.correct,
        wrongProblems: localStats.value.wrong,
        accuracy: localStats.value.accuracy,
        continuousDays: originalContinuousDays  // 保留原始值
      }
      
      console.log('📝 最终显示的统计数据:', stats.value)
    }
  } catch (error) {
    console.error('加载学习数据失败:', error)
  } finally {
    loading.value = false
  }
}

function changeTab(tab) {
  currentTab.value = tab
  currentPage.value = 1
}

// 计算本地统计数据（基于去重后的题目）
const localStats = computed(() => {
  const total = uniqueProblems.value.length
  const correct = uniqueProblems.value.filter(p => p.isCorrect).length
  const wrong = total - correct
  const accuracy = total > 0 ? Math.round((correct * 100) / total) : 0
  
  return {
    total,
    correct,
    wrong,
    accuracy
  }
})

function changePage(page) {
  currentPage.value = page
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 头像上传功能
function handleAvatarClick() {
  avatarInput.value.click()
}

async function handleAvatarChange(event) {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    toastRef.value?.show({
      title: '上传失败',
      message: '请选择图片文件',
      type: 'error'
    })
    return
  }

  // 验证文件大小 (2MB)
  if (file.size > 2 * 1024 * 1024) {
    toastRef.value?.show({
      title: '上传失败',
      message: '图片大小不能超过2MB',
      type: 'error'
    })
    return
  }

  try {
    const formData = new FormData()
    formData.append('avatar', file)

    const { data } = await uploadAvatar(formData)
    
    // 更新用户信息
    userStore.setUserInfo({
      ...userInfo.value,
      avatar: data.avatar
    })

    toastRef.value?.show({
      title: '上传成功',
      message: '头像已更新',
      type: 'success'
    })
  } catch (error) {
    console.error('上传头像失败:', error)
    toastRef.value?.show({
      title: '上传失败',
      message: error.message || '请稍后重试',
      type: 'error'
    })
  } finally {
    // 清空input值，允许重复上传同一文件
    event.target.value = ''
  }
}

function goToProblem(problemId) {
  router.push(`/problems/${problemId}`)
}

function formatTime(timeStr) {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time

  if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 604800000) {
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return time.toLocaleDateString()
  }
}
</script>

<style scoped lang="scss">
.my-learning-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.top-navbar {
  background: white;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .navbar-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 16px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .navbar-left {
    .back-btn {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 16px;
      background: #f5f5f5;
      border-radius: 8px;
      text-decoration: none;
      color: #333;
      font-size: 14px;
      transition: all 0.3s;
      
      &:hover {
        background: #e8e8e8;
      }
    }
  }
  
  .navbar-center {
    h1 {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }
  
  .navbar-right {
    .user-info {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .user-avatar-small {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        object-fit: cover;
      }
      
      .avatar-placeholder-small {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        font-weight: bold;
      }
      
      .user-name {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
    }
  }
}

.stats-container {
  max-width: 1200px;
  margin: 24px auto;
  padding: 0 24px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  
  .stat-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    }
    
    .stat-icon {
      font-size: 36px;
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f7fa;
      border-radius: 12px;
    }
    
    .stat-info {
      flex: 1;
      
      .stat-value {
        font-size: 28px;
        font-weight: 700;
        color: #333;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #999;
      }
    }
  }
}

.filter-container {
  max-width: 1200px;
  margin: 0 auto 24px;
  padding: 0 24px;
  
  .filter-tabs {
    background: white;
    border-radius: 12px;
    padding: 8px;
    display: flex;
    gap: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    
    .filter-tab {
      flex: 1;
      padding: 12px 24px;
      background: transparent;
      border: none;
      border-radius: 8px;
      font-size: 15px;
      color: #666;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        background: #f5f7fa;
      }
      
      &.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        font-weight: 600;
      }
    }
  }
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px 40px;
  
  .loading, .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: #999;
    
    svg {
      margin-bottom: 16px;
      
      &.spin {
        animation: spin 1s linear infinite;
        color: #667eea;
      }
    }
    
    p {
      font-size: 16px;
    }
  }
  
  .problems-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    .problem-item {
      background: white;
      border-radius: 12px;
      padding: 20px;
      cursor: pointer;
      transition: all 0.3s;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      &:hover {
        transform: translateX(4px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
      }
      
      .problem-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
        
        .problem-id {
          font-size: 13px;
          color: #999;
          font-weight: 500;
        }
        
        .problem-status {
          padding: 4px 12px;
          border-radius: 12px;
          font-size: 13px;
          font-weight: 500;
          
          &.correct {
            background: #e8f5e9;
            color: #4caf50;
          }
          
          &.wrong {
            background: #ffebee;
            color: #f44336;
          }
        }
      }
      
      .problem-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 12px;
      }
      
      .problem-meta {
        display: flex;
        align-items: center;
        gap: 16px;
        font-size: 13px;
        color: #999;
        
        .problem-difficulty {
          padding: 2px 8px;
          border-radius: 4px;
          font-weight: 500;
          
          &.easy {
            background: #e8f5e9;
            color: #4caf50;
          }
          
          &.medium {
            background: #fff3e0;
            color: #ff9800;
          }
          
          &.hard {
            background: #ffebee;
            color: #f44336;
          }
        }
        
        .problem-score {
          font-weight: 600;
          color: #667eea;
        }
      }
    }
  }
  
  .pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    margin-top: 32px;
    
    .page-btn {
      padding: 10px 24px;
      background: white;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
      color: #333;
      transition: all 0.3s;
      
      &:hover:not(:disabled) {
        background: #667eea;
        color: white;
        border-color: #667eea;
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
    
    .page-info {
      font-size: 14px;
      color: #666;
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

